class Install {

	static var path = "c:/program files/flashdevelop";

	static function message( msg : String ) {
		neko.Lib.println(msg);
	}

	static function main() {
		var args = neko.Sys.args();
		if( args.length > 1 )
			path = args[0];

		message("Checking path");
		if( !neko.FileSystem.exists(path) )
			throw "FlashDevelop 2.x not found in "+path;
		path += "/";
		if( neko.FileSystem.exists(path+"swfop.dll") )
			throw "FlashDevelop 3.x seems to be installed, please use haxeFD with 2.x version only";

		// copy haxe.xml
		message("Installing syntax file");
		var data = haxe.Resource.getBytes("syntax");
		var xml_file = path+"Settings/Languages/haxe.xml";
		var f = neko.io.File.write(xml_file,true);
		f.write(data);
		f.close();

		// copy haxeProject.dll
		message("Installing plugin");
		var data = haxe.Resource.getBytes("dll");
		var dll_file = path+"Plugins/haxeProject.dll";
		var f = neko.io.File.write(dll_file,true);
		f.write(data);
		f.close();

		// add haXe to Syntax Menu
		message("Adding menu");
		var menu_file = path+"Settings/MainMenu.xml";
		var settings = Xml.parse(neko.io.File.getContent(menu_file));
		var found = false;
		var main = settings.firstElement();
		for( menu in main.elementsNamed("menu") ) {
			if( menu.get("name") == "SyntaxMenu" ) {
				for( b in menu.elementsNamed("button") )
					if( b.get("tag") == "haxe" ) {
						found = true;
						break;
					}
				if( !found ) {
					var x = Xml.createElement("button");
					x.set("label","&amp;haXe");
					x.set("click","ChangeSyntax");
					x.set("tag","haxe");
					menu.insertChild(x,0);
					found = true;

					var f = neko.io.File.write(menu_file,true);
					f.writeString(settings.toString());
					f.close();
				}
			}
		}
		if( !found )
			throw "Syntax menu not found in "+menu_file;

		// add haxe.xml to languages
		message("Registering syntax");
		var lang_file = path+"Settings/ScintillaNET.xml";
		var haxe_lang_file = "@APPDIR/Settings/Languages/haxe.xml";
		var settings = Xml.parse(neko.io.File.getContent(lang_file));
		var found = false;
		var includes = settings.firstElement().elementsNamed("includes").next();
		if( includes == null )
			throw "No includes in "+lang_file;
		for( i in includes.elementsNamed("include") )
			if( i.get("file") == haxe_lang_file ) {
				found = true;
				break;
			}
		if( !found ) {
			var x = Xml.createElement("include");
			x.set("file",haxe_lang_file);
			includes.addChild(x);

			var f = neko.io.File.write(lang_file,true);
			f.writeString(settings.toString());
			f.close();
		}

		// done
		neko.Lib.println("Done");
	}

}
